﻿using NewChillers.Models;
using NewChillers.Models.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NewChillers.ViewModels.ShellViewModel;

namespace NewChillers.Utils
{
    /// <summary>
    /// 事件中心类
    /// </summary>
    public static class AppEventCenter
    {
        // 属性
        private static CommState? _lastCommState; // 设备是否连接 历史状态

        // 用户相关

        // 设备相关

        // 界面相关
        public static event EventHandler<CommStateChangeEventArgs> CommStateChange;

        // 触发方法
        public static void RaiseCommStateChange(object sender, CommState state)
        {
            _lastCommState = state;
            Debug.WriteLine($"触发通讯状态事件: {state}, 订阅者数量: {CommStateChange?.GetInvocationList()?.Length ?? 0}");
            CommStateChange?.Invoke(sender, new CommStateChangeEventArgs(state));
        }

        // 为新订阅者提供获取最后状态的方法
        public static void SubscribeWithLastState(EventHandler<CommStateChangeEventArgs> handler)
        {
            CommStateChange += handler;

            if (_lastCommState.HasValue)
            {
                Debug.WriteLine($"新订阅者立即获取到历史状态: {_lastCommState.Value}");
                // 使用 null 作为 sender，避免引用可能已销毁的对象
                handler?.Invoke(null, new CommStateChangeEventArgs(_lastCommState.Value));
            }
        }

        // 提供状态查询
        public static bool TryGetLastState(out CommState state)
        {
            state = _lastCommState ?? CommState.Disconnected; // 默认值
            return _lastCommState.HasValue;
        }
    }
}
